package com.maxjay.component.simplelist.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.maxjay.common.util.json.JsonParser;
import com.maxjay.component.metadata.model.Record;
import com.maxjay.component.metadata.web.controller.BaseServlet;
import com.maxjay.component.simplelist.model.QueryConditionField;
import com.maxjay.component.simplelist.model.QueryScheme;
import com.maxjay.component.simplelist.service.QuerySchemeService;
import com.maxjay.system.constant.SystemParamKeys;
import com.maxjay.system.core.Application;

/**
 * 简要列表数据获取Servlet，供Ext简要列表使用
 * 
 * @author zhaixm
 *
 */
public class SimpleListDataServlet extends BaseServlet {
	
	private static final long serialVersionUID = 1L;
	
	private static final Logger LOG = Logger.getLogger(SimpleListServlet.class);
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SimpleListDataServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    @SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		QuerySchemeService querySchemeService = Application.getBeanContext().getBean("querySchemeService", QuerySchemeService.class);
		String schemeId = request.getParameter("schemeId");
		int startRow = Integer.valueOf(request.getParameter("start"));
		int endRow = startRow + SystemParamKeys.PAGE_SIZE;
		String rowCountStr = request.getParameter("rowCount");
		QueryScheme queryScheme = Application.getEntityContext().getQuerySchemeFatory().getQueryScheme(schemeId);
		Map<String, Object> paramMap = parseQueryParamMap(queryScheme, request.getParameterMap());
		int rowCount = 0;
		if(StringUtils.isBlank(rowCountStr)) {
			rowCount = querySchemeService.getRecordCount(queryScheme, paramMap);
		} else {
			rowCount = Integer.valueOf(rowCountStr);
		}
		//TODO 修改列表获取方式
		List<Record> records = querySchemeService.getDisplayRecordList(queryScheme, paramMap, startRow, endRow);
		DataStore ds = new DataStore(String.valueOf(rowCount), records);
		LOG.info(JsonParser.getJsonObject(ds).toString());
		outputJsonStream(response, JsonParser.convertObjectToJson(ds));
	}
    
    /**
     * 为适应Ext GridPanel Store的获取方式而创建了该类
     * 
     * @author zhaixm
     *
     */
    public class DataStore {
    	private String totalCount;
    	private List<Map<String, Object>> records = new ArrayList<Map<String,Object>>();
    	public DataStore(String totalCount, List<Record> dataRecords) {
    		this.totalCount = totalCount;
    		for (Record record : dataRecords) {
				records.add(record.getDataMap());
			}
		}
		public String getTotalCount() {
			return totalCount;
		}
		public void setTotalCount(String totalCount) {
			this.totalCount = totalCount;
		}
		public List<Map<String, Object>> getRecords() {
			return records;
		}
		public void setRecords(List<Map<String, Object>> records) {
			this.records = records;
		}
    }
    
    private Map<String, Object> parseQueryParamMap(QueryScheme queryScheme, Map<String, Object> paramArrMap) {
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	for (QueryConditionField conditionField : queryScheme.getConditionFields()) {
    		String paramName = conditionField.getEntityField().getName().toUpperCase();
    		String[] paramValArr = (String[])paramArrMap.get(paramName);
    		if (paramValArr == null) {
				continue;
			}
    		String originalVal = paramValArr[0];
    		paramMap.put(paramName, originalVal);
		}
		return paramMap;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
